import { createRouter, createWebHistory } from 'vue-router'
import { transformRoutes } from '@/utils/dynamicRoutes'
import { getMenuTree } from '@/api/menu'
import { ElMessage } from 'element-plus'

const baseUrl = import.meta?.env?.BASE_URL || process.env?.BASE_URL || '/'

// 基础静态路由
const baseStaticRoutes = [
{
path: '/login',
name: 'Login',
component: () => import('@/views/Login.vue'),
    meta: { hidden: true, title: '登录页' }
  },
  {
    path: '/404',
name: 'NotFound',
component: () => import('@/views/404.vue'),
    meta: { hidden: true, title: '页面不存在' }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(baseUrl),
  routes: baseStaticRoutes,
  scrollBehavior: () => ({ top: 0 })
})

let isRoutesBuilt = false

export const buildFullRoutes = async () => {
  if (isRoutesBuilt) return true

  try {
    const response = await getMenuTree()
    if (!response || response.code !== 200 || !Array.isArray(response.data)) {
      throw new Error('菜单数据错误')
    }

    const dynamicRoutes = transformRoutes(response.data)

    // 1. 首页路由单独定义（使用绝对路径，避免相对路径冲突）
    const homeRoute = {
      path: '/dashboard', // 关键：使用绝对路径，确保始终匹配 /dashboard
      name: 'Dashboard',  // 确保名称唯一
      component: () => import('@/views/dashboard/index.vue'),
      meta: {
        title: '首页',
        icon: 'Home',
        order: -1, // 置顶
        visible: '0'
}
}

// 2. Layout主路由（包含首页和动态路由）
const layoutRoute = {
    path: '/',
        name: 'Layout',
        component: () => import('@/views/Layout.vue'),
        redirect: '/dashboard', // 明确重定向到首页绝对路径
        children: [
        homeRoute, // 首页作为子路由
        ...dynamicRoutes
    ]
}

// 清空并重新添加路由
router.getRoutes().forEach(route => router.removeRoute(route.name))
baseStaticRoutes.forEach(route => router.addRoute(route))
router.addRoute(layoutRoute)

// 3. 关键：404路由必须最后添加，避免拦截正常路径
router.addRoute({
    path: '/:pathMatch(.*)*',
        redirect: '/404',
        meta: { hidden: true }
})

// 验证首页路由
const home = router.getRoutes().find(r => r.name === 'Dashboard')
// console.log('首页路由验证:', {
//     path: home?.path,
//         component: home?.components?.default?.toString() // 确认组件路径
// })

isRoutesBuilt = true
return true
} catch (error) {
    // console.error('路由构建失败:', error)
    ElMessage.error(`菜单加载失败：${error.message}`)
    return false
}
}

// 路由守卫
router.beforeEach(async (to, from, next) => {
    document.title = to.meta.title ? `${to.meta.title} - 系统` : '系统'

    const whiteList = ['/login', '/404']
    if (whiteList.includes(to.path)) {
        return next()
    }

    const token = localStorage.getItem('token')
    if (!token) {
        return next('/login')
    }

    if (!isRoutesBuilt) {
        const success = await buildFullRoutes()
        return success ? next({ ...to, replace: true }) : next('/dashboard')
    }

    // 额外验证：如果跳转路径为空或错误，强制跳首页
    if (to.path === '/' || to.path === '*') {
        return next('/dashboard')
    }

    next()
})

router.onError(error => {
    console.error('路由错误:', error)
    ElMessage.error('页面加载失败，请刷新重试')
})

export default router
